﻿using Azure;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using WebApiServices.Models;

namespace WebApiServices.Controllers {

    /// <summary>
    /// 产品信息查询控制器
    /// </summary>
    [ApiController]
    [Route("api/[action]")]
    public class ProductInfoController : BaseController {

        private readonly IFreeSql _freeSql;
        private readonly ILogger<ProductInfoController> _logger;
        private readonly IConfiguration _configuration;

        /// <summary>
        /// 产品信息查询控制器
        /// </summary>
        /// <param name="freeSql"></param>
        /// <param name="logger"></param>
        public ProductInfoController(IFreeSql freeSql, ILogger<ProductInfoController> logger, IConfiguration configuration) {
            _freeSql = freeSql;
            _logger = logger;
            _configuration = configuration;
        }

        /// <summary>
        /// 根据箱码获取产品信息
        /// </summary>
        /// <param name="productRequest"></param>
        /// <returns></returns>
        [HttpPost(Name = "GetProductInfoByBoxCode")]
        public IActionResult GetProductInfoByBoxCode([FromBody] ProductRequest productRequest) {
            
            if (productRequest.BoxCodesStr.Contains("'")) {
                productRequest.BoxCodesStr = productRequest.BoxCodesStr.Replace("'", "''");//防止SQL注入问题
            }

            string[] boxCodeArr = productRequest.BoxCodesStr.Split(',');

            if (boxCodeArr.Length <= 0) {
                return base.ToResponse(ResultCode.PARAM_ERROR);
            }

            if (boxCodeArr.Any(o => string.IsNullOrEmpty(o))) {
                return base.ToResponse(ResultCode.PARAM_ERROR, "参数错误！");
            }

            if (boxCodeArr.Any(o => !o.Contains('$'))) {
                return base.ToResponse(ResultCode.PARAM_ERROR, "参数格式错误！");
            }

            try {

                // 生成SQL查询语句
                string sql = $@"select AbsCode,Code,BoxCode,PackageTime 
                                from [dbo].[PackageResult] p
                                where p.BoxCode in ({string.Join(",", Enumerable.Range(0, boxCodeArr.Length).Select(o => $"@BoxCode_{o}"))})";

                var selParams = Enumerable.Range(0, boxCodeArr.Length).Select(o => new KeyValuePair<string, object>($"@BoxCode_{o}", boxCodeArr[o])).ToDictionary();

                var res = _freeSql.Ado.ExecuteDataTable(sql, selParams);

                var returnData = GetApiResult(ResultCode.SUCCESS, res);
                returnData.Add("source", _configuration["Model"] ?? "");

                return base.ToResponse(returnData);

            } catch (Exception ex) {

                _logger.LogError(ex.Message);

                return base.ToResponse(ResultCode.GLOBAL_ERROR, "查询异常！");

            }
        }

    }

    /// <summary>
    /// 请求参数模型
    /// </summary>
    public class ProductRequest {
        /// <summary>
        /// 装箱码，多个请用","分隔
        /// </summary>
        public required string BoxCodesStr { get; set; }
    }

}
